import Request from '../../../utils/request.js'
import { navigateTo } from "../../../utils/util.js"
const app = getApp()
const store = app.store

function initSubMenuDisplay() {
  return ['dtl-hidden', 'dtl-hidden'];
}
function getNowFormatDate(date) {
  date = date || new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }

  return [year, month, strDate].join('-');
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    newdepartmentlist2: [],
    secondlist: [],
    firstindex: -1,
    secondindex: -1,
    xzks: '选择科室',
    xzpx: "默认",
    subMenuDisplay: initSubMenuDisplay(),
    entryID: 1,
    deptId: '',
    SdeptType: '',
    ClinicName: '',
    ClinicIDCopy:'',
    SdeptTypeCopy: '',
    doctorsData: [],
    doctorSources: {},
    mode: 0,
    modeType: 1,
    dates: [],
    requesting: false,
    end: false,
    emptyShow: false,
    emptyText: "暂无数据",
    bottomText: '点击左上方“选择科室”，可查看科室下的全部医生呢',
  },

  RequestDocList: function (deptId, entryID, SdeptType) {
    this.setData({
      requesting: true,
      emptyShow: false,
      end: false,
    });

    if (entryID == 2){
      Request.getRequest('/favoriteDoctor/findByUserId', { clinicId: deptId }).then(data => {
        let doctorinfolist = data.data
        if (!Array.isArray(doctorinfolist) && doctorinfolist) {
          let a = []
          a.push(doctorinfolist)
          doctorinfolist = a;
        } else if (!doctorinfolist){
          doctorinfolist = []
        }
        doctorinfolist.forEach(function (element) {
          element.AmOrPm = element.amOrPm
          element.ChargeRegister = element.chargeRegister
          element.ChargeRegisterAll = element.chargeRegisterAll
          element.ChargeTreatment = element.chargeTreatment
          element.CheckDT = element.checkDT
          element.ClinicID = element.clinicID
          element.ClinicName = element.clinicName
          element.DiagTreatTypeCode = element.diagTreatTypeCode
          element.DiagTreatTypeName = element.diagTreatTypeName
          element.DoctorDesc = element.doctorIntroduction
          element.DoctorID = element.doctorID
          element.DoctorName = element.doctorName
          element.DoctorPosition = element.workCodeName
          element.SchedulingID = element.schedulingID
          element.SpecialDiseasesCode = element.specialDiseasesCode
          element.StopOutPatFlag = element.stopOutPatFlag
          element.SurplusNum = element.surplusNum
          element.visitTotal = element.visTotals
          element.ChargeRegister = element.ChargeRegisterAll//会诊费用
          element.ChargeRegisterAll = element.ChargeRegisterAll
          element.StopOutPatFlag = element.schedulingID ? 0 : 1//是否停诊
          element.logo = store.getState().doctorSettings.showAvatar ? app.globalData.ENVIRONMENT_CONFIG.imgBaseUrl + element.doctorId + '.jpg' : '/images/doctor-icon.png'
        })
        console.log("doctorinfolist2", doctorinfolist)

        this.setData({
          requesting: false,
          emptyShow: true,
          end: true,
          doctorsData: doctorinfolist ? doctorinfolist : []
        });
      }, error => {
        this.setData({
          requesting: false,
          emptyShow: true,
          end: true,
          doctorsData: []
        });
      })
    }else{
      Request.postRequest('/api/common/findTadministrativeOrDoctorListNoPage', {
        pageNo: '1',
        pageSize: '10000',
        searchStr: '',
        clinicId: deptId
      }, undefined, true).then(data => {
        let doctorinfolist = []
        data.data.forEach((item, index) => {
          doctorinfolist.push({
            appraise: item.averageLevel * 1,//评分
            visitTotal: item.visTotals,//问诊量
            DoctorDesc: item.doctorIntroduction,//擅长
            DiagTreatTypeName: item.visStatusDescrib,//问诊方式
            StopOutPatFlag: item.SchedulingID ? 0 : 1,//是否停诊
            DoctorPosition: item.workCodeName,
            DoctorName: item.doctorName,
            DoctorID: item.doctorId,
            ClinicName: item.clinicName,
            ClinicID: item.clinicId,
            DeptType: item.deptType,
            ChargeRegister: item.ChargeRegisterAll,//会诊费用
            ChargeRegisterAll: item.ChargeRegisterAll,
            logo: store.getState().doctorSettings.showAvatar ? app.globalData.ENVIRONMENT_CONFIG.imgBaseUrl + item.doctorId + '.jpg' : '/images/doctor-icon.png'
          });
        });
        this.setData({
          requesting: false,
          emptyShow: true,
          end: true,
          doctorsData: doctorinfolist ? doctorinfolist : []
        });

        // 若为日期模式，则加载号源
        this.data.mode == 1 && this.getDoctorSchedule()
      }, error => {
        console.log('出错了')
        this.setData({
          requesting: false,
          emptyShow: true,
          end: true,
          doctorsData: [],
          doctorSources: {}
        })
        // 没有医生信息也需要调用排班信息
        this.getDoctorSchedule()
      })
    }
  },
  getDoctorSchedule() {
    let dates = this.data.dates
    let doctorSources = {}

    // 清空数据
    this.setData({
      doctorSources
    })
    wx.showLoading()

    let params = {
      hosDistId: app.globalData.district,
      clinicID: this.data.deptId,
      deptType:this.data.deptType,
      startDT: dates[0].fullDate,
      endDT: dates[dates.length - 1].fullDate
    }
    Request.getRequest('/appointment/appointmentScheduling', params, undefined, true).then(res => {
      wx.hideLoading()
      let info = res
      let scheduleList = info.RecordList.RecordInfo
      console.log("scheduleList",scheduleList)
      scheduleList.forEach(item => {
        let scheduleDate = item.ON_DUTY_TIME.split(' ')[0]
        if (!doctorSources[scheduleDate]) {
          doctorSources[scheduleDate] = {
            scheduledAmDoctors: [],
            scheduledPmDoctors: []
          }
        }

        let doctorInfo = {
          doctorId: item.DoctorID,
          deptId: item.ClinicID,
          deptType: item.DeptType || '',
          doctorName: item.DoctorName,
          doctorPosition: item.DOCTOR_TYPENAME,
          sourceDate: scheduleDate.split('-').map(item => parseInt(item)).join('-'),
          REGISTER_AMOUNT: item.REGISTER_AMOUNT,
          surplusNum: item.APPOINTMENT_COUNTNO.split(",",1) > 0 ? item.APPOINTMENT_COUNTNO.split(",",1) : 0
        }
        if ((item.CLINIC_DURATIONNAME.indexOf('上午') != -1 || item.CLINIC_DURATIONNAME == '全天')) 
          doctorSources[scheduleDate].scheduledAmDoctors.push({
            ...doctorInfo,
            sourceCode: 'AM',
          })

        if ((item.CLINIC_DURATIONNAME.indexOf('下午') != -1 || item.CLINIC_DURATIONNAME == '全天')) {
          doctorSources[scheduleDate].scheduledPmDoctors.push({
            ...doctorInfo,
            sourceCode: 'PM',
          })
        }
      })

      this.setData({
        doctorSources,
      })
    }).catch(err => {
      wx.hideLoading()
    })
  },
  switchModeType(evt) {
    let type = evt.currentTarget.dataset.type
    this.setData({
      modeType: type
    })
  },
  getTimeMinutes(time) {
    if (time.includes('-')) {
      time = time.split(' ')[1].substr(0, 5)
    }
    let timeArr = time.split(':')
    return timeArr[0] * 60 + timeArr[1] * 1
  },
  goDoctorDetail(evt) {
    let doctor = evt.currentTarget.dataset.item
    let disabled = evt.currentTarget.dataset.disabled
    !disabled && navigateTo({
      url: '/pages/activity/activityShow/activityShow?DoctorId=' + doctor.doctorId + '&deptId=' + this.data.deptId + '&deptType=' + this.data.deptType + '&scheduleDate=' + doctor.sourceDate + '&optionCode=' + doctor.sourceCode +'&chargeRegisterAll=' + doctor.REGISTER_AMOUNT
     //url: '/pages/activity/activityDetail/activityDetail?DoctorId=' + doctor.doctorId + '&deptId=' + this.data.deptId + '&deptType=' + this.data.deptType + '&scheduleDate=' + doctor.sourceDate + '&optionCode=' + doctor.sourceCode +'&chargeRegisterAll=' + doctor.REGISTER_AMOUNT
    })
  },
  // 刷新数据
  refresh() {
    this.RequestDocList(this.data.deptId, this.data.entryID, this.data.SdeptType);
    // 隐藏所有弹出菜单
    this.setData({
      subMenuDisplay: initSubMenuDisplay()
    });
  },
  // 加载更多
  more() {
    console.log("more");
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('路由入参：', options)
    this.setData({
      deptId: options.item ? options.item : "",
      SdeptType: options.SdeptType ? options.SdeptType : "",
      deptType: options.dept_type ? options.dept_type : "",
      ClinicName: options.clinicName ? options.clinicName : "",
      xzks: options.clinicName ? options.clinicName : "选择科室",
      mode: options.mode ? options.mode : 0,
    });
    this.setData({
      entryID: options.entryID ? options.entryID : 1
    });
    if (options.mode == 1) {
      wx.setNavigationBarTitle({
        title: '选择日期',
      })
    }

    let supClinicName = options.supClinicName

    Request.getRequest('/appointment/depts',  { yqdm: app.globalData.district }).then(data => {
      let departmentlist = data.data
      if (!Array.isArray(departmentlist)) {
        let a = []
        a.push(departmentlist)
        departmentlist = a;
      }

      var array = [];
      for (var i = 0; i < departmentlist.length; i++) {
        departmentlist[i].DEPT_PARENT === '0' && array.push({
          topId: departmentlist[i].DEPT_CHILD,
          name: departmentlist[i].DEPT_NAME,
        })
      }

      var newdepartmentlist = [];
      for (var j = 0; j < array.length; j++) {
        newdepartmentlist[j] = {}
        newdepartmentlist[j].SupClinicName = array[j].name;
        newdepartmentlist[j].index = j;
        newdepartmentlist[j].newDepartArray = [];
        supClinicName === array[j].name && this.setData({
          firstindex: j
        })
        for (var i = 0; i < departmentlist.length; i++) {
          let deptItem = departmentlist[i]
          if (deptItem.DEPT_PARENT === array[j].topId) {
            newdepartmentlist[j].newDepartArray.push({
              Clinic: deptItem.DEPT_NAME,
              ClinicID: deptItem.DEPT_CODE,
              SupClinicName: array[j].name,
              dept_type: deptItem.DEPT_TYPE,
              index: newdepartmentlist[j].newDepartArray.length > 0 ? newdepartmentlist[j].newDepartArray.length : 0
            })
          }
        }
      }
      this.setData({
        newdepartmentlist2: newdepartmentlist
      });
      // 如果由科室列表跳转至本页，选中所选科室
      if (this.data.firstindex !== -1) {
        let secondlist = newdepartmentlist[this.data.firstindex].newDepartArray
        let secondindex = -1
        secondlist.some((item, index) => {
          if (item.Clinic === options.clinicName) {
            secondindex = index
            return true
          }
        })
        this.setData({
          secondlist: secondlist,
          secondindex: secondindex
        })
      }
      console.log("newdepartmentlist", newdepartmentlist)
    })

    // this.RequestDocList(this.data.deptId, this.data.entryID, this.data.SdeptType);
  },
  initDates(currentDate) {
    let week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    let today = currentDate || new Date()
    let dates = []
    for (let i = 0; i < 8; i++) {
      let date = new Date()
      date.setDate(today.getDate() + i)
      dates.push({
        day: week[date.getDay()],
        date: [date.getMonth() + 1, date.getDate()].join('/'),
        fullDate: getNowFormatDate(date)
      })
    }
    this.setData({
      dates,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    Request.getRequest('/system/time').then(res => {
      let dateStr = res.data.replace(/-/g, "/")
      let currentDate = new Date(dateStr)
      this.initDates(currentDate)
      this.RequestDocList(this.data.deptId, this.data.entryID, this.data.SdeptType);
    })
  },

  // tapdepartcancel: function () {
  //
  // },

  toDoctotList: function (e) {
    console.log(e)
    let item = e.currentTarget.dataset['index'];
    console.log(item)
    this.setData({
      secondindex: item.index
    });
    this.setData({
      ClinicName: item.Clinic,
      ClinicIDCopy: item.ClinicID,
      SdeptTypeCopy: item.SdeptType
    });
  },
  clickthisitem: function (e) {
    let item = e.currentTarget.dataset['index'];
    console.log(item)
    this.setData({
      secondindex: -1
    });
    this.setData({
      firstindex: item.index
    });
    this.setData({
      secondlist: item.newDepartArray
    });
    this.setData({
      ClinicIDCopy: '',
      SdeptTypeCopy: ''
    });
  },

  tapSelectMenu: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var newSubMenuDisplay = initSubMenuDisplay();

    if (this.data.subMenuDisplay[index] == 'dtl-hidden') {
      newSubMenuDisplay[index] = 'dtl-show';
    } else {
      newSubMenuDisplay[index] = 'dtl-hidden';
    }        // 设置为新的数组
    this.setData({
      subMenuDisplay: newSubMenuDisplay
    });
  },
  tapSubMenu: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    // 隐藏所有弹出菜单
    this.setData({
      subMenuDisplay: initSubMenuDisplay()
    });
  },
  hideshade: function (e) {

  },
  tapdepartsubmit: function (e) {
    this.setData({
      deptId: this.data.ClinicIDCopy,
      SdeptType: this.data.SdeptTypeCopy
    });
    this.RequestDocList(this.data.deptId, this.data.entryID, this.data.SdeptType);
    // 隐藏所有弹出菜单
    this.setData({
      subMenuDisplay: initSubMenuDisplay(),
      xzks: this.data.ClinicName
    });
  },
  tapdepartcancel: function (e) {
    this.setData({
      deptId: '',
      SdeptType: ''
    });
    this.RequestDocList(this.data.deptId, this.data.entryID, this.data.SdeptType);
    // 隐藏所有弹出菜单
    this.setData({
      subMenuDisplay: initSubMenuDisplay(),
      xzks: '选择科室',
      secondlist: [],
      firstindex: -1,
      secondindex: -1,
    });
  },
})
